package br.com.massai.model.beans;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.SQLException;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import br.com.massai.model.business.FileBusiness;
import br.com.massai.model.exceptions.ErrorCore;
import br.com.massai.model.exceptions.MessageCore;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.utils.FacesUtil;

@ViewScoped
@ManagedBean
public class FileBean implements Serializable {

	private static final long serialVersionUID = -6695877355700820695L;

	private UploadedFile file;

	@EJB private FileBusiness fileBusiness;

	public void handleFileUpload(FileUploadEvent event) throws IOException{
		readFile(event.getFile().getInputstream());
	}

	public void readFile(InputStream inputStream) throws SystemException, IOException {
		try{
			fileBusiness.importFile(inputStream);
			FacesUtil.registrarMensagem(MessageCore.SUCESS_IMPORT_FILE.getCode());

		} catch (SQLException e) {
			throw new SystemException(ErrorCore.ERROR_DATABASE_CONNECTION);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}
}